package main

import (
	"encoding/json"
	"github.com/nsqio/go-nsq"
	"log"
)

type myMessageHandler struct {
}

// HandleMessage implements the Handler interface.
func (h *myMessageHandler) HandleMessage(m *nsq.Message) error {
	if len(m.Body) == 0 {
		// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.
		// In this case, a message with an empty body is simply ignored/discarded.
		return nil
	}

	nsqData := NsqMsg{}
	json.Unmarshal(m.Body, &nsqData)

	room, ok := rooms.rooms[nsqData.RoomId]
	if ok {
		room.broadcastMsg <- nsqData.Msg
	}

	return nil
}

func NewConsumer() {
	config := nsq.NewConfig()
	consumer, err := nsq.NewConsumer(roomDanMuMsg, "channel", config)
	if err != nil {
		log.Fatal(err)
	}

	// Set the Handler for messages received by this Consumer. Can be called multiple times.
	// See also AddConcurrentHandlers.
	consumer.AddHandler(&myMessageHandler{})

	// Use nsqlookupd to discover nsqd instances.
	// See also ConnectToNSQD, ConnectToNSQDs, ConnectToNSQLookupds.
	//err = consumer.ConnectToNSQLookupd("127.0.0.1:4161")
	err = consumer.ConnectToNSQD("127.0.0.1:4150")
	if err != nil {
		log.Fatal(err)
	}
}
